package cn.ronghuanet.course.service.impl;

import cn.ronghuanet.basic.domain.AlicloudOSSProperties;
import cn.ronghuanet.basic.service.impl.BaseServiceImpl;
import cn.ronghuanet.basic.util.AjaxResult;
import cn.ronghuanet.course.domain.Course;
import cn.ronghuanet.course.domain.CourseDetail;
import cn.ronghuanet.course.mapper.CourseDetailMapper;
import cn.ronghuanet.course.service.ICourseService;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 业务实现类：
 */
@Service
public class CourseServiceImpl extends BaseServiceImpl<Course> implements ICourseService {
    @Autowired
    private AlicloudOSSProperties alicloudOSSProperties;

    @Autowired
    private CourseDetailMapper courseDetailMapper;


    @Override
    public AjaxResult upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = alicloudOSSProperties.getEndpoint();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // 填写Bucket名称，例如examplebucket。
        String bucketName = alicloudOSSProperties.getBucketName();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String s = UUID.randomUUID().toString();
        String objectName = "images/" + s + "-" + file.getOriginalFilename();
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        File file1 = new File("");
        try {

            file1 = convertMultipartFileToFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, alicloudOSSProperties.getAccessKey(), alicloudOSSProperties.getSecretKey());

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file1);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(result);
            ResponseMessage response = result.getResponse();
            return AjaxResult.me().setResultObj(objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    public File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convFile = null;
        InputStream inputStream = file.getInputStream();
        convFile = new File(file.getOriginalFilename());
        OutputStream outputStream = new FileOutputStream(convFile);
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        return convFile;
    }
}
